package com.naiterui.ehp.bs.doctor.service.impl;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bs.doctor.dao.IDrAppH5MapperDao;
import com.naiterui.ehp.bs.doctor.domain.DrAppH5Mapper;
import com.naiterui.ehp.bs.doctor.exception.ExceptionCodes;
import com.naiterui.ehp.bs.doctor.service.IDrAppH5MapperService;
import com.naiterui.ehp.bs.doctor.vo.H5InfoVO;
import com.naiterui.ehp.bs.doctor.vo.param.AppH5ParamVO;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * app和h5版本映射关系业务处理接口实现
 *
 * @author gongbaoqiang
 * @date 2019/7/15 16:47
 * @since 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdDrAppH5MapperServiceImpl implements IDrAppH5MapperService {

    private final IDrAppH5MapperDao appH5MapperDao;

    @Value("${ehp.domain.doctorH5}")
    private String doctorH5Host;

    @Override
    public H5InfoVO findH5ZipByAppVerion(String h5V, String appV, Integer type) throws BusinessException {
        //根据appV和type获取最新的映射记录，app和h5升级存在不一致场景, h5升级后维护最新映射记录
        DrAppH5Mapper mapper = this.appH5MapperDao.findPreByAppVersionAndDeviceTyp(appV, type);
        //记录不存在时，获取最新的一条配置记录
        if (mapper == null) {
            log.info("根据appV和type获取最新的映射记录不存在：h5V={}, appV={}, type={}", h5V, appV, type);
            mapper = this.appH5MapperDao.findNewsOne();
            if (mapper == null) {
                log.error("无配置记录，请联系H5升级相关人员配置映射数据");
                throw new BusinessException(ExceptionCodes.PARAM_ERROR);
            }
        }
        H5InfoVO infoVO = new H5InfoVO();
        //校验h5版本号：参数h5V小于记录的h5版本，则返回新版本号和地址，否则返回空
        if (StringUtils.compare(h5V, mapper.getH5Version()) < 0) {
            infoVO.setH5V(mapper.getH5Version());
            infoVO.setZip(this.doctorH5Host + mapper.getH5Url());
        } else {
            infoVO.setH5V(h5V);
            infoVO.setZip("");
        }
        log.info("appV和h5最新记录：h5v={}, zip={}", mapper.getH5Version(), mapper.getH5Url());
        return infoVO;
    }

    @Override
    public void add(AppH5ParamVO vo) {
        DrAppH5Mapper mapper = new DrAppH5Mapper();
        BeanUtils.copyProperties(vo, mapper);
        mapper.setCreatedAt(new Date());
        this.appH5MapperDao.save(mapper);
    }

}
